package com.bobi.tfca.ui.mainnavigation.home.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentOrganizeActivityBinding
import com.bobi.tfca.network.response.ActivityResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.util.RealPathUtil
import com.gingold.basislibrary.utils.BasisTimesUtils
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.time.LocalDateTime

class OrganizeActivityFragment :
    BaseFragment<FragmentOrganizeActivityBinding, OrgActivityFragmentVM>(
        FragmentOrganizeActivityBinding::inflate,
        OrgActivityFragmentVM::class.java,
        true
    ) {

    private var body: MultipartBody.Part? = null
    private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent>
    private lateinit var imageView: ImageView

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            if (permissions.all { it.value }) {
                // 如果所请求的所有权限都被授予，则执行相应的操作，比如打开相册
            } else {
                // 如果有任何一个权限被拒绝，则可以向用户解释为什么需要这些权限，并提供一个再次请求的机会
                Toast.makeText(requireActivity(), "选择图片需要权限", Toast.LENGTH_SHORT).show()
            }
        }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun checkPermissions(): Boolean {
        val isAllGranted = REQUIRED_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(
                requireContext(),
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
        // 如果权限没有授予，请求权限
        if (!isAllGranted) {
            requestPermissionLauncher.launch(REQUIRED_PERMISSIONS)
            return false
        } else {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            return true
        }
    }

    // 在适当的时候调用请求权限的方法
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun openPictureChooser() {
        if (checkPermissions()) {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            // 点击图片后，更改图片
            // 打开图片选择器
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            imagePickerLauncher.launch(intent)
        }
    }


    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentOrganizeActivityBinding,
        viewModel: OrgActivityFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        // 设置顶部样式
        setTopPanelStyle(binding)

        // 上传图片按钮
        imageView = binding.ivActivityPicture
        imageView.setOnClickListener {
            uploadImage()
        }

        // 这是第一步，没有上一步
        binding.previousStep.visibility = View.GONE

        // 设置日期选择器监听
        setDateListener(binding)

        binding.nextStep.setOnClickListener {

            publicViewModel!!.organizeActivity.activityName = binding.etTitle.text.toString()
            publicViewModel!!.organizeActivity.activityPlace = binding.etPlace.text.toString()
            val limitedNum = binding.etLimitedNum.text.toString().toIntOrNull()
            if (limitedNum == null) {
                Toast.makeText(
                    requireActivity(),
                    "限制人数应为数字",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            if (limitedNum < 2) {
                Toast.makeText(
                    requireActivity(),
                    "限制人数应该大于1",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            publicViewModel!!.organizeActivity.limitedNum = limitedNum
            // 报名时间和活动时间
            publicViewModel!!.organizeActivity.actStartTime =
                binding.tvActStartDate.text.toString() + " " + binding.tvActStartTime.text.toString()
            publicViewModel!!.organizeActivity.actEndTime =
                binding.tvActEndDate.text.toString() + " " + binding.tvActEndTime.text.toString()
            publicViewModel!!.organizeActivity.signStartTime =
                binding.tvSignStartDate.text.toString() + " " + binding.tvSignStartTime.text.toString()
            publicViewModel!!.organizeActivity.signEndTime =
                binding.tvSignEndDate.text.toString() + " " + binding.tvSignEndTime.text.toString()
            if (!BasisTimesUtils.isLaterThanCurrentTime(publicViewModel!!.organizeActivity.signStartTime)) {
                Toast.makeText(
                    requireActivity(),
                    "报名开始时间不能早于当前时间",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            if (!BasisTimesUtils.isLaterThanCurrentTime(publicViewModel!!.organizeActivity.actStartTime)) {
                Toast.makeText(
                    requireActivity(),
                    "活动开始时间不能早于当前时间",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            if (BasisTimesUtils.compareTimes(publicViewModel!!.organizeActivity.signStartTime, publicViewModel!!.organizeActivity.signEndTime) >= 0) {
                Toast.makeText(
                    requireActivity(),
                    "报名开始时间不能晚于结束时间",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            if (BasisTimesUtils.compareTimes(publicViewModel!!.organizeActivity.actStartTime, publicViewModel!!.organizeActivity.actEndTime) >= 0) {
                Toast.makeText(
                    requireActivity(),
                    "活动开始时间不能晚于结束时间",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }
            // 跳转下一步
            requireActivity().findNavController(R.id.app_nav)
                .navigate(R.id.action_organizeActivityFragment_to_orgActConditionFragment)
        }

        // 注册图片选择器
        registerImagePickerResult(viewModel!!)
    }

    private fun initTimeText(binding: FragmentOrganizeActivityBinding) {
        val nowYear: Int = LocalDateTime.now().year
        val nowMonth: Int = LocalDateTime.now().monthValue
        val nowDay: Int = LocalDateTime.now().dayOfMonth
        // 将月份和日期格式化为两位数字的形式
        val formattedMonth = String.format("%02d", nowMonth)
        val formattedDayOfMonth = String.format("%02d", nowDay)
        val date = "$nowYear-$formattedMonth-$formattedDayOfMonth"
        binding.tvSignStartDate.text = date
        binding.tvActStartDate.text = date
        binding.tvSignEndDate.text = date
        binding.tvActEndDate.text = date
        val hour = LocalDateTime.now().hour
        val minute = LocalDateTime.now().minute
        val formattedTime = "%02d:%02d".format(hour, minute)
        binding.tvActStartTime.text = formattedTime
        binding.tvActEndTime.text = formattedTime
        binding.tvSignStartTime.text = formattedTime
        binding.tvSignEndTime.text = formattedTime
    }

    private fun setDateListener(binding: FragmentOrganizeActivityBinding) {
        // 初始日期显示
        initTimeText(binding)

        // 日期选择器
        binding.tvActStartDate.setOnClickListener {
            showYearMonthDayPicker(binding.tvActStartDate)
        }
        binding.tvActEndDate.setOnClickListener {
            showYearMonthDayPicker(binding.tvActEndDate)
        }
        binding.tvSignStartDate.setOnClickListener {
            showYearMonthDayPicker(binding.tvSignStartDate)
        }
        binding.tvSignEndDate.setOnClickListener {
            showYearMonthDayPicker(binding.tvSignEndDate)
        }

        // 时间选择器
        binding.tvSignStartTime.setOnClickListener {
            showTimerPicker(binding.tvSignStartTime)
        }
        binding.tvActStartTime.setOnClickListener {
            showTimerPicker(binding.tvActStartTime)
        }
        binding.tvSignEndTime.setOnClickListener {
            showTimerPicker(binding.tvSignEndTime)
        }
        binding.tvActEndTime.setOnClickListener {
            showTimerPicker(binding.tvActEndTime)
        }
    }

    /**
     * 小时分钟选择
     */

    /**
     * 时间选择
     */
    private fun showTimerPicker(tvTime: TextView) {
        BasisTimesUtils.showTimerPickerDialog(
            context,
            true,
            "请选择时间",
            12,
            0,
            true,
            object : BasisTimesUtils.OnTimerPickerListener {
                override fun onConfirm(hourOfDay: Int, minute: Int) {
                    val formattedTime = "%02d:%02d".format(hourOfDay, minute)
                    tvTime.text = formattedTime
                }

                override fun onCancel() {
                }
            })
    }


    /**
     * 年月日选择
     */
    private fun showYearMonthDayPicker(tvDte: TextView) {
        val nowYear: Int = LocalDateTime.now().year
        val nowMonth: Int = LocalDateTime.now().monthValue
        val nowDay: Int = LocalDateTime.now().dayOfMonth

        BasisTimesUtils.showDatePickerDialog(
            context,
            BasisTimesUtils.THEME_HOLO_DARK,
            "请选择年月日",
            nowYear,
            nowMonth,
            nowDay,
            object : BasisTimesUtils.OnDatePickerListener {
                override fun onConfirm(year: Int, month: Int, dayOfMonth: Int) {
                    // 将月份和日期格式化为两位数字的形式
                    val formattedMonth = String.format("%02d", month)
                    val formattedDayOfMonth = String.format("%02d", dayOfMonth)
                    val date = "$year-$formattedMonth-$formattedDayOfMonth"
                    tvDte.text = date
                }

                override fun onCancel() {
                }
            })
    }

    private fun registerImagePickerResult(viewModel: OrgActivityFragmentVM) {
        imagePickerLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val selectedImageUri: Uri? = result.data?.data
                    selectedImageUri?.let {
                        val file = getFileFromUri(selectedImageUri)
                        val requestFile = RequestBody.create(MediaType.parse("image/*"), file)
                        body = MultipartBody.Part.createFormData("file", file!!.name, requestFile)
                        if (body != null) {
                            LogUtil.i("选择了图片")
                            // 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
                            viewModel.uploadImageToServer(
                                this, publicViewModel!!, body!!,
                                imageView
                            )
                        } else {
                            LogUtil.i("图片未选择")
                        }
                    }
                }
            }
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentOrganizeActivityBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            publicViewModel!!.resetOrganizeActivity()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.text = "活动信息"
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun uploadImage() {
        openPictureChooser()
    }

    private fun getFileFromUri(uri: Uri): File? {
        val filePath = RealPathUtil.getRealPath(requireActivity(), uri)
        return if (filePath != null) File(filePath) else null
    }
}